package org.korosoft.rusalad.syncnrun.tools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * Syncnrun utility methods.
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class Utils {
    public static int getObjectSize(Object o) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            oos.close();
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return baos.size();
    }

    public static String getPaddingObject(int size) {
        String s = "";
        while (getObjectSize(s) < size) {
            s += "\0";
        }
        return s;
    }

    public static String getHumanReadableDataVolume(long bytes) {
        if (bytes < 1024) {
            return String.format("%d B", bytes);
        }
        double b = bytes / 1024;
        if (b < 1024) {
            return String.format("%.1f KiB", b);
        }
        b /= 1024;
        if (b < 1024) {
            return String.format("%.1f MiB", b);
        }
        b /= 1024;
        if (b < 1024) {
            return String.format("%.1f GiB", b);
        }
        b /= 1024;
        return String.format("%.1f TiB", b);
    }

    private Utils() {
    }
}
